package JUnitTests;

import static org.junit.Assert.*;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import DataStorageClasses.ReviewEntry;
import Database.DatabaseConnector;
import ExceptionClasses.InvalidReviewerAuthenticationException;

public class ReviewEntryConnectorTests 
{
	private static DatabaseConnector dbConnector;
	private static String userName;
	private static String userPassword;
	private static String userEmail;
	private static String businessName;
	private static String businessPassword;
	
	@BeforeClass public static void initialize()
	{
		dbConnector = new DatabaseConnector();
		dbConnector.connect();
		
		userName = "DummyUserName";
		userPassword = "userPassword";
		userEmail = "userEmail";
		businessName = "TesterBusiness";
		businessPassword = "businessPassword";
		
		dbConnector.addBusiness(businessName, businessPassword, null, null, null, null, null, null, null, null, null);
		dbConnector.addReviewer(userName, userPassword, userEmail);
		
		try {
			dbConnector.subscribeToBusiness(userName, userPassword, businessName);
		} catch (InvalidReviewerAuthenticationException e) {
			fail();
		}
	}
	
	@AfterClass public static void destroy()
	{
		try {
			dbConnector.removeReviewer(userName, userPassword);
		} catch (InvalidReviewerAuthenticationException e) {
			fail();
		}
		
		dbConnector.removeBusiness(businessName, businessPassword);
		dbConnector.disconnect();
	}
	
	@Test public void addReview()
	{
		String wrongPassword = "wrongPassword";
		String content = "some stuff";
		Date date = new Date(0);
		try {
			dbConnector.addReview(userName, userPassword, businessName, content, date);
		} catch (InvalidReviewerAuthenticationException e) {
			fail();
		}
		
		try {
			dbConnector.addReview(userName, wrongPassword, businessName, content, date);
			fail();
		} catch (InvalidReviewerAuthenticationException e) {
		}
	}
	
	@Test public void testGetReviewsByDate()
	{
		String content = "some content";
		
		Calendar cal = Calendar.getInstance();
		
		cal.set(1988, 1, 22);
		Date date1 = new Date(cal.getTimeInMillis());
		
		cal.set(2011, 3, 4);
		Date date2 = new Date(cal.getTimeInMillis());
		
		cal.set(2011, 3, 5);
		Date date3 = new Date(cal.getTimeInMillis());
		
		try {
			dbConnector.addReview(userName, userPassword, businessName, content, date2);
			dbConnector.addReview(userName, userPassword, businessName, content, date3);
			dbConnector.addReview(userName, userPassword, businessName, content, date1);
		} catch (InvalidReviewerAuthenticationException e) {
			fail();
		}
		
		ArrayList<ReviewEntry> entries = dbConnector.getReviewsByDate(5, businessName);
		
		for (int i = 0; i<2; i++) {
			assertTrue(entries.get(i).getDate().after(entries.get(i+1).getDate()));
		}
	}
}
